## 1 Show that KOF correlates with more major trade partners.
## Appendix N

kofmajorexporters <- ggplot(final.data, aes(x=KOFEcGIdf.0, y=count.major.exporters)) +
  geom_point(alpha=0.05,na.rm = TRUE,position="jitter")+ 
  geom_smooth(size=1.5)+
  geom_rug(col="#999999",alpha=0.05, size=1) +
  stat_cor(method = "pearson", label.x = 0, label.y = 30, size=10)+
  xlab("KOF")+ylab("Major trade partners")+
  theme_bw(base_size = 20) + theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

kofmajorimporters <- ggplot(final.data, aes(x=KOFEcGIdf.0, y=count.major.importers)) +
  geom_point(alpha=0.05,na.rm = TRUE,position="jitter")+ 
  geom_smooth(size=1.5)+
  geom_rug(col="#999999",alpha=0.05, size=1) +
  stat_cor(method = "pearson", label.x = 0, label.y = 30, size=10)+
  xlab("KOF")+ylab("Major trade partners")+
  theme_bw(base_size = 20) + theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

dir.create("./AppendixMaterials/CorrelationPlot")
ggsave(file = "AppendixMaterials/CorrelationPlot/kofmajorexporters.pdf",
       kofmajorexporters, width=10, height=6)
ggsave(file = "AppendixMaterials/CorrelationPlot/kofmajorimporters.pdf",
       kofmajorimporters, width=10, height=6)

## 2. Plot major trade partners for different countries
## Used to generate Figure 1 in the paper 
## can also be used to generate figures for other countries

## 2.a generate country names
final.dytrade <- read.dta("RawData/dytrade.dta", convert.underscore = TRUE)
names(final.dytrade)[3] <- "year"
# may comment this out to look at a longer historical span
final.dytrade <- subset(final.dytrade, year > 1994 & year < 2014)

final.dytrade$cname1 <- countrycode(final.dytrade$ccode1,'cown','country.name') 
final.dytrade$cname2 <- countrycode(final.dytrade$ccode2,'cown','country.name') # this might be responsible for differing values for imports.all and imports.value; the latter includes imports from non-ccode states


## 2.b function for plotting number of major trade partners over time
## input: country name
## output: plotdata of major trade partners by import, export, both, either
plot_dat_fun <- function(country="China"){
  temp.major <- final.dytrade[final.dytrade$cname1==country&
                                (final.dytrade$major.import+final.dytrade$major.export)!=0,]
  
  temp.major$major.both <- as.numeric((temp.major$major.import*temp.major$major.export)==1)
  temp.major$major.either <- as.numeric((temp.major$major.import+temp.major$major.export)!=0)
  
  temp.count <- ddply(temp.major, .(year), summarize,
                      import.count=sum(major.import),
                      export.count=sum(major.export),
                      both.count=sum(major.both),
                      either.count=sum(major.either))
  
  temp.count.long <- reshape(temp.count, varying=c("import.count","export.count","both.count","either.count"),
                             times=c("import","export","both","either"),
                             v.name="count", timevar="type", direction="long")
  
  return(temp.count.long)
}
china.plotdat <- plot_dat_fun("China")
us.plotdat <- plot_dat_fun("United States")
#sgp.plotdat <- plot_dat_fun("Singapore")
## plot the change of either overtime
majorovertime.plot <- ggplot(china.plotdat[china.plotdat$type=="either",], aes(x=year, y=count)) +
                      theme_bw() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(),panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
                      geom_line(aes(linetype="solid"), # Line type depends on cond
                      size = 1)+
                      geom_line(data=us.plotdat[us.plotdat$type=="either",],
                                aes(x=year, y=count,linetype="dashed"), # Line type depends on cond
                                size = 1)+
                      scale_linetype_discrete(name="Country",
                                              labels=c("US","China"))+
                      theme(legend.position = c(.1,.8))

dir.create("./Figures")
ggsave(file = "Figures/majorovertime.pdf", majorovertime.plot, width=10, height=6.3)


## 2.c function for generating whether a country is major trade partners over time
overtime_plot <- function(country="United States",type="either"){
  temp.major <- final.dytrade[final.dytrade$cname1==country&
                                (final.dytrade$major.import+final.dytrade$major.export)!=0,]
  
  temp.major$major.both <- as.numeric((temp.major$major.import*temp.major$major.export)==1)
  temp.major$major.either <- as.numeric((temp.major$major.import+temp.major$major.export)!=0)
  
  temp.major <- temp.major[,c("state.b","year",paste0("major.",type))]
  names(temp.major)[3] <- "majortype"
  temp.major <- ddply(temp.major, .(state.b), mutate, 
                 type.sum=sum(majortype))
  temp.major <- temp.major[temp.major$type.sum!=0,]
  if (country=="China"){temp.major <- temp.major[temp.major$state.b!="CHN",]} # To guard against double counting china because of hongkong
  q.plot <- qplot(year, reorder(state.b,type.sum), data = na.omit(temp.major), fill = as.factor(majortype), geom = "raster")+theme_bw() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(),panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+ theme(legend.position="none")+scale_fill_manual(values=c("#FFFFFF", "#000000"), name="Major")
  q.plot
}

op_us_ex <- overtime_plot(country="United States", type="export") +ggtitle("(a1) US Export")
op_us_im <- overtime_plot(country="United States", type="import") +ggtitle("(a2) US Import")
op_us_bt <- overtime_plot(country="United States", type="both")+ggtitle("(a3) US Both")

op_cn_ex <- overtime_plot(country="China", type="export")+ggtitle("(b1) China Export")
op_cn_im <- overtime_plot(country="China", type="import")+ggtitle("(b2) China Import")
op_cn_bt <- overtime_plot(country="China", type="both")+ggtitle("(b3) China Both")

grid_arrange_shared_legend(op_us_ex,op_us_im,op_us_bt,op_cn_ex,op_cn_im,op_cn_bt,ncol=3,nrow=2,position="right")

us_either <- overtime_plot(country="United States", type="either") +scale_fill_manual(values=c("#000000","#FFFFFF"), name="Major")+ggtitle("(a) US Major Partners")
China_either <- overtime_plot(country="China", type="either") +scale_fill_manual(values=c("#000000","#FFFFFF"), name="Major")+ggtitle("(b) China Major Partners")
us_china_either <- grid.arrange(us_either,China_either,nrow=2)
majorallin1<-grid.arrange(majorovertime.plot,us_china_either,nrow=1, left = "Count")

ggsave(file = "Figures/majorovertimeallin1.pdf", majorallin1, width=10, height=8)



